package com.decent.ejfadmin.collectcard.controller;

import cn.decent.component.shiro.entity.Admin;
import cn.decent.component.shiro.service.AdminService;
import com.decent.ejfadmin.collectcard.entity.ManualClearing;
import com.decent.ejfadmin.collectcard.entity.SupplyCardQueryBean;
import com.decent.ejfadmin.collectcard.service.CollectCardDetailService;
import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.common.bean.Page;
import com.decent.ejfadmin.common.enums.OperationTypeEnum;
import com.decent.ejfadmin.common.enums.Operator;
import com.decent.ejfadmin.user.service.UserService;
import com.decent.ejfadmin.utils.Httpclient;
import com.decent.ejfadmin.utils.ParamUtil;
import com.decent.ejfadmin.utils.PlatConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;


/**
 * 收卡明细
 *
 * @author weicx
 * @date 2018/07/19
 */
@RestController
@RequestMapping("CollectCardDetail")
@Slf4j
public class CollectCardDetailController {
    @Autowired
    private CollectCardDetailService collectCardDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    /**
     * 收卡明细查询
     *
     * @param supplyCardQueryBean 销卡订单查询参数封装实体
     * @param page                分页组件
     * @return
     */
    @RequestMapping("/queryReceiveList")
    public Page queryReceiveList(SupplyCardQueryBean supplyCardQueryBean, Page page) {
        try {
            ParamUtil.verifyRequestParam(supplyCardQueryBean.getStartTime(), supplyCardQueryBean.getEndTime(), page);
            if (StringUtils.isNotBlank(supplyCardQueryBean.getUserAccount())) {
                String userid = userService.getUserId(supplyCardQueryBean.getUserAccount());
                String getUserResult = "toomuch";
                if (StringUtils.isBlank(userid) || StringUtils.equals(getUserResult, userid)) {
                    return userService.dealUserid(userid);
                }
                supplyCardQueryBean.setIds(userid);
            }
            return collectCardDetailService.queryReceiveList(supplyCardQueryBean, page);
        } catch (Exception e) {
            log.warn("收卡明细查询异常: [{}]", e);
            page.setResultList(new ArrayList<>());
            page.setTotal(0);
            return page;
        }
    }


    /**
     * 修改收卡订单状态
     *
     * @param batchIds
     * @param ids
     * @param operate
     * @param productType 操作类型,1:批次失败,2:卡号失败,3批次再次提交
     * @param remark      等待慢速试充：1:批次失败,2:卡号失败
     * @return
     */
    @RequestMapping("setFail")
    public synchronized MessageBean setFail(@RequestParam(value = "batchId", required = false) String[] batchIds,
                                            @RequestParam(value = "id", required = false) String[] ids,
                                            Integer operate, Integer productType, String remark) {
        try {
            Admin adminUser = adminService.getCurrentAdmin();
            if (adminUser == null) {
                return MessageBean.fail("请登录后操作");
            }
            if (operate == null) {
                return MessageBean.fail("请选择操作类型");
            }

            if (!ArrayUtils.contains(new int[]{1, 2, 3}, operate)) {
                return MessageBean.fail("未识别的操作类型");
            }

            Integer handleType = 3;
            if (handleType.equals(operate)) {
                if (productType >= Operator.SINOPEC.getType() && productType <= Operator.CNPC.getType()) {
                    //加油卡productType:300-310
                    return MessageBean.fail("未识别的操作类型");
                }
                if (productType > Operator.CNPC.getType()) {
                    //权益productType:>310
                    return collectCardDetailService.equityBatchResubmission(ids, productType);
                }
            }
            //三网productType<300
            String batchIdsStr = null;
            String idsStr = null;
            //按批次号处理
            if ((OperationTypeEnum.BATCH_FAIL.getStatus().equals(operate) || OperationTypeEnum.BATCH_RESUBMIT.getStatus().equals(operate))) {
                if ((batchIds == null || batchIds.length == 0)) {
                    return MessageBean.fail("请选择要操作的记录");
                } else {
                    batchIdsStr = "'".concat(StringUtils.join(batchIds, "','")).concat("'");
                }
            }
            //按卡号处理
            if (OperationTypeEnum.CARD_FAIL.getStatus().equals(operate)) {
                if ((ids == null || ids.length == 0)) {
                    return MessageBean.fail("请选择要操作的记录");
                } else {
                    idsStr = "'".concat(StringUtils.join(ids, "','")).concat("'");
                }
            }

            int row = collectCardDetailService.setFail(idsStr, batchIdsStr, operate, remark);
            return MessageBean.success("成功操作" + row + "条记录");
        } catch (Exception e) {
            log.warn("修改收卡订单（预判面值不符置失败）异常[{}]", e);
            return MessageBean.fail("修改出错:(");
        }
    }

    /**
     * 收卡明细查询同步功能
     *
     * @param ids ID
     * @return
     */
    @RequestMapping("synchronousCard")
    public MessageBean synchronousCard(String[] ids) {
        try {
            Admin adminUser = adminService.getCurrentAdmin();
            if (adminUser == null) {
                return MessageBean.fail("请登录后操作");
            }
            if (ids == null || ids.length == 0) {
                return MessageBean.fail("请选择要操作的记录");
            }
            int row = collectCardDetailService.synchronousCard(StringUtils.join(ids, ","));
            return MessageBean.success("成功操作" + row + "条记录");
        } catch (Exception e) {
            log.warn("收卡明细查询同步功能 异常: [{}]", e);
            return MessageBean.fail();
        }
    }

    /**
     * 收卡明细导出
     *
     * @param card     销卡订单查询参数封装实体
     * @param response
     * @return MemberMessage
     */
    @RequestMapping("downLoad")
    public void downLoad(SupplyCardQueryBean card, HttpServletResponse response) {
        ServletOutputStream writer = null;
        try {
            response.setCharacterEncoding("GBK");
            response.setContentType("text/html;charset=GBK");
            writer = response.getOutputStream();
            if (org.apache.commons.lang.StringUtils.isBlank(card.getStartTime()) || org.apache.commons.lang.StringUtils.isBlank(card.getEndTime())) {
                String msg = "<script >alert('输入起始时间！');</script>";
                IOUtils.write(msg.getBytes("GBK"), writer);
                writer.flush();
                return;
            }
            if (StringUtils.isNotBlank(card.getUserAccount())) {
                String userid = userService.getUserId(card.getUserAccount());
                if (userid == null || StringUtils.equals("toomuch", userid)) {
                    log.warn(" 没有匹配到会员！");
                    return;
                }
                if (StringUtils.equals("toomuch", userid)) {
                    log.warn(" 匹配到的会员过多！");
                    return;
                }
                card.setIds(userid);
            }
            Date begin = DateUtils.parseDate(card.getStartTime(), "yyyy-MM-dd hh:mm:ss");
            Date end = DateUtils.parseDate(card.getEndTime(), "yyyy-MM-dd hh:mm:ss");
            if (DateUtils.addDays(begin, 1).before(end)) {
                String msg = "<script >alert('导出时间范围限定在1天内！');</script>";
                IOUtils.write(msg.getBytes("GBK"), writer);
                writer.flush();
                return;
            }
            response.setCharacterEncoding("GBK");
            response.setContentType("text/html;charset=GBK");
            collectCardDetailService.downLoad(response, writer, card);
        } catch (Exception e) {
            log.warn("收卡明细列表导出出错[{}]", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * 停止/开启电信预判异常直接走试充
     *
     * @param status 1:直接走试充  0:异常n次走试充
     * @return
     */
    @RequestMapping(value = "changeTelecomJudge", method = RequestMethod.POST)
    public MessageBean changeTelecomJudge(Integer status) {
        try {
            return collectCardDetailService.changeTelecomJudge(status);
        } catch (Exception e) {
            log.warn("停止/开启预判异常直接走试充失败[{}]", e);
            return MessageBean.fail();
        }
    }

    /**
     * 查询电信预判异常直接走试充 true 直接走试充
     *
     * @return
     */
    @RequestMapping(value = "getTelecomJudge")
    public boolean getTelecomJudge() {
        try {
            return collectCardDetailService.getTelecomJudge();
        } catch (Exception e) {
            log.warn("查询预判异常直接走试充[{}]  ", e);
            return true;
        }
    }

    /**
     * 电信卡预判
     *
     * @param cardId 电信卡号
     * @return
     */
    @RequestMapping("getTeleComCardStatus")
    public String getTeleComCardStatus(String cardId) {
        StringBuffer url = new StringBuffer();
        url.append(PlatConfigUtil.getProperty("card_supply_info.properties", "TELECOM_STATUS_URL"));
        url.append("?cardId=").append(cardId);
        String response = Httpclient.get(url.toString(), 1000, 3000);
        return response;
    }

    /**
     * 订单异步
     *
     * @param orderId 会员id
     * @return
     */
    @RequestMapping("orderAsyn")
    public MessageBean orderAsyn(String orderId) {
        try {
            return collectCardDetailService.orderAsyn(orderId);
        } catch (Exception e) {
            log.warn("订单异步异常: [{}]", e);
            return MessageBean.fail(e.getMessage());
        }
    }

    /**
     * 权益订单置失败
     *
     * @param ids    订单id
     * @param remark 备注
     * @return
     */
    @RequestMapping("equitySetFail")
    public MessageBean equitySetFail(Long[] ids, String remark) {
        try {
            if (ids == null || ids.length < 1) {
                return MessageBean.fail("请选择要操作的记录");
            }
            if (StringUtils.isBlank(remark)) {
                return MessageBean.fail("备注不能为空");
            }
            return collectCardDetailService.equitySetFail(ids, remark);
        } catch (Exception e) {
            log.warn("权益订单置失败异常: [{}]", e);
            return MessageBean.fail(e.getMessage());
        }
    }

    /**
     * 权益订单成功置失败
     *
     * @param ids    订单id
     * @param remark 备注
     * @return
     */
    @RequestMapping("equitySuccessToFail")
    public MessageBean equitySuccessToFail(String[] ids, String remark) {
        try {
            if (ids == null || ids.length == 0) {
                return MessageBean.fail("请选择要操作的记录");
            }
            if (StringUtils.isBlank(remark)) {
                return MessageBean.fail("备注不能为空");
            }
            return collectCardDetailService.equitySuccessToFail(ids, remark);
        } catch (Exception e) {
            log.warn("权益订单成功置失败异常: [{}]", e);
            return MessageBean.fail(e.getMessage());
        }
    }

    /**
     * 权益订单置成功
     *
     * @param ids 订单id
     * @return
     */
    @RequestMapping("equitySetSuccess")
    public MessageBean equitySetSuccess(String[] ids) {
        try {
            if ((ids == null || ids.length == 0)) {
                return MessageBean.fail("请选择要操作的记录");
            }
            return collectCardDetailService.equitySetSuccess(ids);
        } catch (Exception e) {
            log.warn("权益订单置成功异常: [{}]", e);
            return MessageBean.fail(e.getMessage());
        }
    }

    /**
     * 设置备注
     *
     * @param id
     * @param remark
     * @param remarkType
     * @return
     */
    @RequestMapping(value = "setRemark")
    public MessageBean setRemark(Long id, String remark, String remarkType) {
        try {
            if (id == null || StringUtils.isBlank(remark) || StringUtils.isBlank(remarkType)) {
                return MessageBean.fail("参数有误");
            }
            return collectCardDetailService.setRemark(id, remark, remarkType);
        } catch (Exception e) {
            log.warn("CollectCardDetailController setRemark Error  ", e);
            return MessageBean.fail(e.getLocalizedMessage());
        }
    }


    /**
     * 权益手动补结算
     *
     * @param manualClearing
     * @return
     */
    @RequestMapping("manualClearing")
    public synchronized MessageBean manualClearing(ManualClearing manualClearing) {
        try {
            if (Objects.isNull(manualClearing.getApplyType())) {
                return MessageBean.fail("请选择申请类型！");
            }
            return collectCardDetailService.manualClearing(manualClearing);
        } catch (Exception e) {
            log.warn("权益手动补结算异常:manualClearing[{}] {}", manualClearing, e, e);
            return MessageBean.fail(e.getMessage());
        }
    }
}
